package com.bainarm.library_fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link LogFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class LogFragment extends Fragment {

    private EditText logEditText;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_log, container, false);
        logEditText = view.findViewById(R.id.logEditText);
        return view;
    }

    public void appendLog(String logMsg) {
        String currentLog = logEditText.getText().toString();
        // 如果日志超过2000行，则替换现有日志
        if (currentLog.split("\n").length > 2000) {
            currentLog = currentLog.substring(currentLog.indexOf("\n") + 1);
        }
        // 添加新的日志
        currentLog += logMsg + "\n";
        logEditText.setText(currentLog);
        // 滚动到最新日志处
        logEditText.setSelection(logEditText.getText().length());
    }
}